from typing import Any

import oss2
from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError


class HtmlToOssProvider(ToolProvider):
    def _validate_credentials(self, credentials: dict[str, Any]) -> None:
        try:
            # 获取必需的OSS凭证
            access_key_id = credentials.get('oss_access_key_id')
            access_key_secret = credentials.get('oss_access_key_secret')
            bucket_name = credentials.get('oss_bucket_name')
            endpoint = credentials.get('oss_endpoint')
            
            # 验证必需字段
            if not access_key_id:
                raise ToolProviderCredentialValidationError("OSS Access Key ID is required")
            if not access_key_secret:
                raise ToolProviderCredentialValidationError("OSS Access Key Secret is required")
            if not bucket_name:
                raise ToolProviderCredentialValidationError("OSS Bucket Name is required")
            
            # 如果没有提供endpoint，使用默认值
            if not endpoint:
                endpoint = "oss-cn-hangzhou.aliyuncs.com"
            
            # 验证OSS连接
            auth = oss2.Auth(access_key_id, access_key_secret)
            bucket = oss2.Bucket(auth, endpoint, bucket_name)
            
            # 测试连接 - 尝试获取bucket信息
            try:
                bucket.get_bucket_info()
            except oss2.exceptions.NoSuchBucket:
                raise ToolProviderCredentialValidationError(f"Bucket '{bucket_name}' does not exist")
            except oss2.exceptions.AccessDenied:
                raise ToolProviderCredentialValidationError("Access denied. Please check your OSS credentials")
            except Exception as e:
                raise ToolProviderCredentialValidationError(f"Failed to connect to OSS: {str(e)}")
                
        except ToolProviderCredentialValidationError:
            raise
        except Exception as e:
            raise ToolProviderCredentialValidationError(f"Credential validation failed: {str(e)}")
